import router from "@/router";
import axios from "axios";
import {ElMessage} from "element-plus";
// import {decryptAndGet} from "@/utils/crypto";

const request = axios.create({
  // baseURL: 'http://192.168.119.201:8095',
  // baseURL: 'http://localhost:8095',
  baseURL:'/api',
  withCredentials:false,// 允许跨域,跨域时是否需要凭证
  timeout: 600000  // 后台接口超时时间
})

// request 拦截器
// 可以自请求发送前对请求做一些处理
request.interceptors.request.use(config => {
  const isFormData = config.data instanceof FormData

  if (!isFormData) {
    config.headers['Content-Type'] = 'application/json;charset=utf-8';
  }

  const user = JSON.parse(localStorage.getItem('code_user') || '{}')
  config.headers['token'] = user.accessToken || ''
  config.headers['roleId'] = localStorage.getItem('currentOwnerId') || ''
  return config
}, error => {
  return Promise.reject(error)
});


// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
  response => {
    // 如果是 Blob 文件，不解析，直接返回整个 response
    const type = response.request?.responseType;
    if (type === 'blob') {
      return response;
    }

    let res = response.data;
    // 兼容服务端返回的字符串数据
    if (typeof res === 'string') {
      res = res ? JSON.parse(res) : res
    }
    if(res.code===500 ||res.code===401 || res.code===403){
      ElMessage.error(res.msg)
      localStorage.removeItem('code_user')
      localStorage.removeItem('menuRoutes')
      localStorage.removeItem('currentOwnerId')
      router.push('/login')
    }else if(res.code===202){
      ElMessage.error(res.msg)
    }
    else{
      return res
    }
  },
  error => {
    console.log('err' + error.response)
    return Promise.reject(error)
  }
)

export default request
